<template>
  <div id="preRepair" class="preRepair">
    <cells v-if="carShow">
      <!-- 车辆信息 -->
      <div class="pre-drive-car" layout="row" layout-align="space-between center" v-tap="{methods: goSelectCar}">
        <div layout="row" layout-align="space-between center">
          <!-- image -->
          <div>
            <img :src="car.image" v-if="car.image">
            <img :src="defaultCarImg" v-else>
          </div>

          <!-- detail -->
          <div class="txt">
            <h2>{{ car.name || '车型未知'}}</h2>
          </div>
        </div>
        <!-- >箭头 -->
        <div class="link" style=" line-height: 50px;">
          <img :src="more" class="mu-icon material-icons more-img">
        </div>
      </div>
      <cell label="姓名" :value="info.name" v-tap="{ methods: editInfo, inputType: 1 }"></cell>
      <cell label="称谓" :value="info.gender | genderFilter" v-tap="{methods: editInfo, inputType: 2 }"></cell>
      <cell label="手机号" :value="info.mobile" v-tap="{methods: editInfo, inputType: 3 }"></cell>
      <cell label="到店时间" :value="dateTime" v-tap="{methods: showDateTime}"></cell>
      <!-- cell高度无法扩展, 暂时定制实现 -->
      <div v-if="appointmentType == 'repair'" class="pre-repair-cell" layout="row" layout-align="space-between center" v-tap="{methods: toAppointmentItem}">
        <div class="" layout="row" layout-align="space-between center" :style="{'max-width': appointmentItemsChoosed.length == 0 ? '90%' : '100%'}">
          <div class="label">维修项目</div>
          <div class="content">{{appointmentItemsChoosed | showName(appointmentItems)}}</div>
        </div>
        <!-- >箭头 -->
        <img :src="more" class="mu-icon material-icons more-img" v-if="appointmentItemsChoosed.length == 0">
      </div>
      <cell v-if="appointmentType == 'protect'" label="行驶路程(km)" :value="info.drivingRange" v-tap="{methods: editInfo, inputType: 5 }"></cell>
      <cell v-if="appointmentType != 'try'" label="车牌号" :value="info.plateNumber" v-tap="{methods: editInfo, inputType: 4 }"></cell>
    </cells>

    <!-- button -->
    <div layout="row" layout-align="center center" style="margin: 20px 0;">
      <mu-flat-button label="立即预约" backgroundColor="#FB8713" color="#FFF" v-tap="{methods: createAppointment}" />
    </div>

    <!-- 隐藏, 供弹出展示 -->
    <!-- 时间选择 -->
    <date-time :isShow="dateTimeShow" @closeDateTime="dateTimeShow=false" @getDateTime="getDateTime"></date-time>

    <!-- 信息编辑 -->
    <icar-dialog :isShow="dialogShow" @dialogClose="dialogClose" class="info-edit">
      <div class="info-content">
        <!-- text -->
        <mu-text-field :label="title" :hintText="placeholder" v-model="value" v-if="type == 1" :fullWidth="true" underlineFocusClass="info-edit-input" />
        <!-- radio -->
        <div layout="row" layout-align="space-around center" v-if="type == 2">
          <!-- <mu-radio label="先生" name="group" nativeValue="0" v-model="value" iconClass="info-edit-checked"   />
          <mu-radio label="女士" name="group" nativeValue="1" v-model="value" iconClass="info-edit-checked"   /> -->
          <icar-radio label="先生" nativeValue="0" v-model="value"></icar-radio>
          <icar-radio label="女士" nativeValue="1" v-model="value"></icar-radio>
        </div>
      </div>
      <!-- button -->
      <div layout="row" layout-align="center center" class="full-button">
        <mu-flat-button label="确定" backgroundColor="#FB8713" color="#FFF" v-tap="{methods: getValue}" />
      </div>
    </icar-dialog>

    <!-- 维修项目 -->
    <grid-list v-if="appointmentItemsShow">
      <div slot="title" class="grid-title">请选择</div>
      <div v-if="appointmentItems.length > 0">
        <div v-for="(item, index) in appointmentItems" :key="index" style="position: relative;">
          <div class="item repair">
            <icar-checkbox :label="item.name" labelClass="repair-label" :nativeValue="item.id" v-model="appointmentItemsChoosed_temp"></icar-checkbox>
          </div>
        </div>
      </div>
      <div slot="foot" class="grid-cancel">
        <button v-tap="{methods:appointmentItemsClose}">取消</button>
        <button v-tap="{methods:getAppointmentItem}">确定</button>
      </div>
    </grid-list>
  </div>
</template>

<script>
// obj
import wx from "weixin-js-sdk";
// components
import cells from "components/cells";
import cell from "components/cell";
import dateTime from "components/dateTimePicker/dateTimePicker";
import icarDialog from "components/dialog/dialog";
import gridList from "components/gridList/gridList";
import icarRadio from "components/radio/radio";
import icarCheckbox from "components/checkbox/checkbox";
// image
import defaultImg from "assets/APP-icon_80.png";
import defaultCarImg from "assets/default_car_icon.png";
import more from "assets/more.svg";
// services
import QueryTestAppointment from "services/appointment/QueryTestAppointment";
import QueryRepairAppointment from "services/appointment/QueryRepairAppointment";
import QueryMaintainAppointment from "services/appointment/QueryMaintainAppointment";
import CreateTestAppointment from "services/appointment/CreateTestAppointment";
import CreateRepairAppointment from "services/appointment/CreateRepairAppointment";
import CreateMaintainAppointment from "services/appointment/CreateMaintainAppointment";
import ListAppointmentItem from "services/appointment/ListAppointmentItem";

export default {
  components: {
    cells,
    cell,
    dateTime,
    icarDialog,
    gridList,
    icarRadio,
    icarCheckbox
  },
  data() {
    return {
      defaultImg,
      defaultCarImg,
      more,
      appointmentType: "",
      car: {}, // 车辆相关信息
      carShow: false,
      // brand: {},
      // serie: {},
      info: {}, // 个人相关信息 姓名 性别 手机号码等
      list: ["先生", "女士"],
      // 时间选择
      dateTimeShow: false,
      dateTime: "",
      // 信息编辑相关
      dialogShow: false,
      title: "", // label type为1时有效1
      value: "", // 信息编辑 值
      type: "1", // 编辑界面的input类型 1-text 2-radio
      placeholder: "", // 提示信息
      inputType: "", // 编辑哪个数据 1-姓名 2-性别 3-手机号 4-车牌号
      // 可维修项目
      appointmentItems: [],
      appointmentItemsChoosed: [],
      appointmentItemsChoosed_temp: [],
      appointmentItemsShow: false
    };
  },
  methods: {
    // 展示时间组件
    showDateTime() {
      this.dateTimeShow = !this.dateTimeShow;
    },
    // 获取时间
    getDateTime(time) {
      this.dateTime = time.join("");
    },
    // 编辑个人信息
    editInfo(params) {
      // inputType 1-姓名 2-性别 3-手机号 4-车牌号 5-行驶路程
      this.inputType = params.inputType;
      if (params.inputType == 1) {
        this.value = this.info.name;
        this.type = "1";
        this.placeholder = "请输入姓名";
      } else if (params.inputType == 2) {
        this.value = this.info.gender;
        this.type = "2";
        this.placeholder = "请选择";
      } else if (params.inputType == 3) {
        this.value = this.info.mobile;
        this.type = "1";
        this.placeholder = "请输入手机号";
      } else if (params.inputType == 4) {
        this.value = this.info.plateNumber;
        this.type = "1";
        this.placeholder = "请输入车牌号";
      } else if (params.inputType == 5) {
        this.value = this.info.drivingRange;
        this.type = "1";
        this.placeholder = "请输入里程数";
      }
      this.dialogShow = true;
    },
    // 获取个人信息
    getValue(value) {
      if (this.inputType == 1) {
        this.info.name = this.value;
        this.info.gender = this.info.gender ? this.info.gender : 0;
      } else if (this.inputType == 2) {
        this.info.gender = this.value;
      } else if (this.inputType == 3) {
        this.info.mobile = this.value;
      } else if (this.inputType == 4) {
        this.info.plateNumber = this.value;
      } else if (this.inputType == 5) {
        this.info.drivingRange = this.value;
      }
      this.dialogClose();
    },
    // dialog关闭事件
    dialogClose() {
      this.dialogShow = false;
    },
    // 重新选择车型
    goSelectCar() {
      this.$router.back();
    },
    // 查询可维修项目
    toAppointmentItem() {
      // init appointmentItemsChoosed
      this.appointmentItemsChoosed_temp = [...this.appointmentItemsChoosed]
      if (this.appointmentItems.length == 0) {
        ListAppointmentItem.bind(this)({}, resp => {
          this.appointmentItems = resp.appointmentItems;
        });
      }
      this.appointmentItemsShow = true;
    },
    // 获取选中的维修项目
    getAppointmentItem(params) {
      this.appointmentItemsChoosed = this.appointmentItemsChoosed_temp
      this.appointmentItemsShow = false;
    },
    // 预约
    createAppointment() {
      // 信息校验
      if (checkAppointmentParams(this, this.appointmentType)) {
        switch (this.appointmentType) {
          case "try":
            createTest(this);
            break;
          case "repair":
            createRepair(this);
            break;
          case "protect":
            createMaintain(this);
            break;
        }
      }
    },
    appointmentItemsClose(){
      this.appointmentItemsShow = false;
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      this.car = JSON.parse(this.$route.query.car);
      // this.brand = JSON.parse(to.query.brand);
      // this.serie = JSON.parse(to.query.serie);

      // 查询基本信息
      this.appointmentType = this.$route.params.is;
      switch (this.appointmentType) {
        case "try":
          queryTest(this);
          break;
        case "repair":
          queryRepair(this);
          break;
        case "protect":
          queryMaintain(this);
          break;
      }
      this.carShow = true;
    });
  },
  filters: {
    genderFilter(value) {
      return ["先生", "女士"][value];
    },
    showName(obj, arr) {
      let tempNames = [];
      let tempArr = arr.filter(item => obj.indexOf(item.id) > -1);
      tempArr.forEach(function (item) {
        tempNames.push(item.name);
      });
      return tempNames.length > 0 ? tempNames.join(" ") : null;
    }
  }
};
// 信息校验
function checkAppointmentParams(vm, type) {
  let result =
    validService(vm, vm.info.name, /^(\w|[^x00-xff])+$/, "请输入姓名") &&
    validService(vm, vm.info.gender, /^(0|1)$/, "请选择称谓") &&
    validService(vm, vm.info.mobile, /^1(\d){10}$/, "请输入11位手机号码") &&
    validService(
      vm,
      vm.dateTime,
      vm.dateTime ? vm.dateTime.length > 0 : false,
      "请输入到店时间"
    ) &&
    validService(
      vm,
      vm.dateTime,
      timevalidService(vm.dateTime),
      "预约时间不能早于当前时间",
      "time"
    ) &&
    (type == "repair"
      ? validService(
        vm,
        vm.appointmentItemsChoosed.length,
        vm.appointmentItemsChoosed.length > 0,
        "请选择维修项目"
      )
      : true) &&
    (type == "protect"
      ? validService(vm, vm.info.drivingRange, /^[1-9]\d*$/, "请输入行驶路程")
      : true) &&
    (type != "try"
      ? validService(
        vm,
        vm.info.plateNumber,
        /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/,
        "请输入车牌号"
      )
      : true);
  return result;
}

/**
 * 信息校验工具函数
 * @augments vm view-model
 * @augments val 校验的值
 * @augments cond 正则 或 Boolean
 * @augments msg 提示信息
 * @augments type 'time': 表示时间校验, 不用正则
 */
function validService(vm, val, cond, msg, type) {
  let result;
  if (String(val)) {
    result = cond instanceof RegExp ? cond.test(val) : cond;
  } else {
    result = false;
  }
  if (!result) {
    vm.$.toast(msg);
  }
  return result;
}

// 与当前时间进行校验
function timevalidService(date) {
  var cdata = new Date();
  var _data = new Date(date.split(" ").join("T"));
  return _data.getTime() > cdata.getTime();
}

//获取车辆预约试驾界面信息
function queryTest(vm) {
  QueryTestAppointment.bind(vm)(
    {
      productId: vm.car.id
    },
    resp => {
      vm.info = resp.testAppointment;
    }
  );
}

//获取车辆维修界面信息
function queryRepair(vm) {
  QueryRepairAppointment.bind(vm)(
    {
      productId: vm.car.id ? "" : vm.user.carId
    },
    resp => {
      vm.info = resp.repairAppointment;
      vm.info.plateNumber = vm.info.plateNumber
        ? vm.info.plateNumber
        : vm.car.plateNumber;
    }
  );
}

// 获取车辆保养界面信息
function queryMaintain(vm) {
  QueryMaintainAppointment.bind(vm)(
    {
      productId: vm.car.id,
      // userId: vm.user.userId,
      carId: vm.car.id ? "" : vm.user.carId
    },
    resp => {
      vm.info = resp.maintanceAppointment;
    }
  );
}

// 预约试驾
function createTest(vm) {
  vm.info.appontmentDate = vm.dateTime;
  vm.info.productId = vm.car.id;
  CreateTestAppointment.bind(vm)(
    {
      testAppointment: vm.info
    },
    resp => {
      vm.$.toast("预约成功");
      // 预约成功, 关闭该微信窗口
      setTimeout(function () {
        isWxEnv(vm);
      }, 500);
    }
  );
}
// 预约维修
function createRepair(vm) {
  vm.info.appontmentDate = vm.dateTime;
  vm.info.productId = vm.car.id;
  let request = {
    // 手机号
    mobile: vm.info.mobile,
    // 姓名
    name: vm.info.name,
    // 行驶公里数 维修不需要该参数
    // drivingRange
    // 称谓
    gender: vm.info.gender,
    // 车牌号
    plateNumber: vm.info.plateNumber,
    // 存疑, 从取值看应该是车型id
    productId: vm.info.productId,
    // 到店时间
    appontmentDate: vm.info.appontmentDate,
    //选择的维修项目 @TODO 暂时传空, 塞值导致接口调用失败
    repairItemIds: vm.appointmentItemsChoosed,
    // repairItemIds: [],
    shopId: vm.user.shop.id,
    userId: vm.user.userId,
    carId: vm.info.productId ? "" : vm.user.carId
    // aItems: vm.appointmentItems
  };
  CreateRepairAppointment.bind(vm)(
    {
      repairAppointment: request
    },
    resp => {
      vm.$.toast("预约成功");
      // 预约成功, 关闭该微信窗口
      setTimeout(function () {
        isWxEnv(vm);
      });
    }
  );
}

// 预约保养
function createMaintain(vm) {
  vm.info.appontmentDate = vm.dateTime;
  vm.info.productId = vm.car.id;
  let request = {
    // 手机号
    mobile: vm.info.mobile,
    // 姓名
    name: vm.info.name,
    // 行驶公里数 维修不需要该参数
    // drivingRange
    // 称谓
    gender: vm.info.gender,
    // 车牌号
    plateNumber: vm.info.plateNumber,
    // 存疑, 从取值看应该是车型id
    productId: vm.info.productId,
    // 到店时间
    appontmentDate: vm.info.appontmentDate,
    // 里程数
    drivingRange: vm.info.drivingRange,
    //选择的维修项目 @TODO 暂时传空, 塞值导致接口调用失败
    // repairItemIds: vm.appointmentItemsChoosed,
    // repairItemIds: [],
    shopId: vm.user.shop.id,
    userId: vm.user.userId,
    carId: vm.info.productId ? "" : vm.user.carId
    // aItems: vm.appointmentItems
  };
  CreateMaintainAppointment.bind(vm)(
    {
      maintanceAppointment: request
    },
    resp => {
      vm.$.toast("预约成功");
      // 预约成功, 关闭该微信窗口
      setTimeout(function () {
        isWxEnv(vm);
      });
    }
  );
}

/**
 * 微信js-sdk 关闭窗口
 */
function isWxEnv(vm) {
  if (vm.$.env == "wxPublic") {
    closeWindow(vm, initWXRequest(vm));
  }
}
function initWXRequest(vm) {
  let signHref = location.href.split("#")[0];
  let signOpenId = vm.$.state;
  let signUrlInfo = encodeURIComponent(signHref);
  let signData = {
    clientType: '3',
    methodName: "QueryJssdkConfig",
    shopId: "",
    userId: "",
    urlInfo: signUrlInfo,
    wechatOpenId: signOpenId
  };
  return signData;
}

function closeWindow(vm, signData) {
  vm.$.wxGet(signData).then(res => {
  // vm.$.get(signData).then(res => {
    res = res.data;
    console.log("res: ", res);
    wx.config({
      debug: true,
      appId: res.appId,
      timestamp: res.timestamp,
      nonceStr: res.nonceStr,
      signature: res.signature,
      jsApiList: ["closeWindow"]
    });
    // wx.closeWindow();
    wx.ready(function () {
      wx.closeWindow();
    });
    wx.error(function (res) {
      // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      // alert("wx res =>" + JSON.stringify(res));
    });
  });
}
</script>

<style lang="scss" scoped>
.pre-drive-car {
  height: auto !important;
  padding: 10px;
  border-bottom: 1px solid #eeeeee;
  img {
    width: 100px;
  }
}
.txt {
  h2 {
    display: inline-block;
    width: 100%;
    float: left;
    font-size: 14px;
    white-space: normal;
    position: relative;
    left: 5px;
    vertical-align: middle;
  }
  h3 {
    float: left;
    position: relative;
    left: 5px;
    font-size: 14px;
    color: red;
    vertical-align: middle;
    span {
      color: black;
    }
  }
}
.full-button {
  button {
    width: 100%;
  }
}
.info-content {
  padding-bottom: 25px;
}
.item.repair {
  padding: 10px;
  font-size: 15px;
  border-bottom: 1px solid #cbcbcb;
  display: flex;
  align-items: center;
}
.pre-repair-cell {
  padding-right: 10px;
  min-height: 45px;
  border-bottom: 1px solid #eeeeee;
  .label {
    padding-left: 14px;
    color: #0c0c0c;
    font-size: 1.1rem;
  }
  .content {
    font-size: 12px;
    color: #6c6c6c;
    max-width: 70%;
    padding-right: 0;
  }
  > div {
    flex: 1 1 90%;
    max-width: 90%;
    max-height: 100%;
    box-sizing: border-box;
  }
}
.more-img {
  width: 15px !important;
  height: 15px;
  margin-left: 10px;
  margin-right: 5px;
}
</style>
<style lang="scss">
.info-edit-checked {
  &.mu-radio-icon-checked,
  &.mu-checkbox-icon-checked {
    color: #f98700;
  }
  &.mu-radio-icon-uncheck,
  &.mu-checkbox-icon-uncheck {
    color: #939393 !important;
  }
}
.info-edit-input {
  background-color: #f98700;
}
.mu-flat-button {
  min-width: 50%;
}
.repair-label {
  padding-left: 20px;
  font-size: 14px;
}
.grid-cancel button {
  background: #fa992e;
  border: 0;
  outline: none;
  padding: 10px 50px;
  color: #fff;
  font-size: 13px;
  border-radius: 3px;
}
</style>

